<template>
  <div class="admin-dashboard">
    <a-page-header title="管理仪表盘" />
    
    <a-row :gutter="[16, 16]">
      <!-- 统计卡片 -->
      <a-col :xs="24" :sm="12" :md="6">
        <a-card>
          <template #title>
            <div class="card-title">
              <user-outlined />
              <span>用户总数</span>
            </div>
          </template>
          <div class="card-content">
            <div class="card-value">{{ statistics.totalUsers }}</div>
            <div class="card-trend" :class="{ 'up': statistics.userGrowth > 0, 'down': statistics.userGrowth < 0 }">
              <arrow-up-outlined v-if="statistics.userGrowth > 0" />
              <arrow-down-outlined v-if="statistics.userGrowth < 0" />
              <span>{{ Math.abs(statistics.userGrowth) }}%</span>
              <span class="trend-period">较上月</span>
            </div>
          </div>
        </a-card>
      </a-col>
      
      <a-col :xs="24" :sm="12" :md="6">
        <a-card>
          <template #title>
            <div class="card-title">
              <crown-outlined />
              <span>付费会员</span>
            </div>
          </template>
          <div class="card-content">
            <div class="card-value">{{ statistics.paidUsers }}</div>
            <div class="card-trend" :class="{ 'up': statistics.paidUserGrowth > 0, 'down': statistics.paidUserGrowth < 0 }">
              <arrow-up-outlined v-if="statistics.paidUserGrowth > 0" />
              <arrow-down-outlined v-if="statistics.paidUserGrowth < 0" />
              <span>{{ Math.abs(statistics.paidUserGrowth) }}%</span>
              <span class="trend-period">较上月</span>
            </div>
          </div>
        </a-card>
      </a-col>
      
      <a-col :xs="24" :sm="12" :md="6">
        <a-card>
          <template #title>
            <div class="card-title">
              <file-text-outlined />
              <span>提示词总数</span>
            </div>
          </template>
          <div class="card-content">
            <div class="card-value">{{ statistics.totalPrompts }}</div>
            <div class="card-trend" :class="{ 'up': statistics.promptGrowth > 0, 'down': statistics.promptGrowth < 0 }">
              <arrow-up-outlined v-if="statistics.promptGrowth > 0" />
              <arrow-down-outlined v-if="statistics.promptGrowth < 0" />
              <span>{{ Math.abs(statistics.promptGrowth) }}%</span>
              <span class="trend-period">较上月</span>
            </div>
          </div>
        </a-card>
      </a-col>
      
      <a-col :xs="24" :sm="12" :md="6">
        <a-card>
          <template #title>
            <div class="card-title">
              <dollar-outlined />
              <span>月收入</span>
            </div>
          </template>
          <div class="card-content">
            <div class="card-value">¥{{ statistics.monthlyRevenue.toLocaleString() }}</div>
            <div class="card-trend" :class="{ 'up': statistics.revenueGrowth > 0, 'down': statistics.revenueGrowth < 0 }">
              <arrow-up-outlined v-if="statistics.revenueGrowth > 0" />
              <arrow-down-outlined v-if="statistics.revenueGrowth < 0" />
              <span>{{ Math.abs(statistics.revenueGrowth) }}%</span>
              <span class="trend-period">较上月</span>
            </div>
          </div>
        </a-card>
      </a-col>
      
      <!-- 图表区域 -->
      <a-col :xs="24" :lg="12">
        <a-card title="用户增长趋势">
          <div ref="userChartRef" style="height: 300px"></div>
        </a-card>
      </a-col>
      
      <a-col :xs="24" :lg="12">
        <a-card title="收入趋势">
          <div ref="revenueChartRef" style="height: 300px"></div>
        </a-card>
      </a-col>
      
      <a-col :xs="24" :md="12">
        <a-card title="会员分布">
          <div ref="membershipChartRef" style="height: 300px"></div>
        </a-card>
      </a-col>
      
      <a-col :xs="24" :md="12">
        <a-card title="提示词分类统计">
          <div ref="promptCategoryChartRef" style="height: 300px"></div>
        </a-card>
      </a-col>
      
      <!-- 最近活动 -->
      <a-col :span="24">
        <a-card title="最近活动">
          <a-list
            :data-source="recentActivities"
            :loading="loading"
            item-layout="horizontal"
          >
            <template #renderItem="{ item }">
              <a-list-item>
                <a-list-item-meta>
                  <template #avatar>
                    <a-avatar :style="{ backgroundColor: item.avatarColor }">
                      {{ item.avatarText }}
                    </a-avatar>
                  </template>
                  <template #title>
                    <a href="#">{{ item.title }}</a>
                  </template>
                  <template #description>
                    <div>{{ item.description }}</div>
                    <div class="activity-time">{{ item.time }}</div>
                  </template>
                </a-list-item-meta>
              </a-list-item>
            </template>
          </a-list>
        </a-card>
      </a-col>
    </a-row>
  </div>
</template>

<script>
import { ref, reactive, onMounted, onUnmounted } from 'vue';
import { 
  UserOutlined, 
  CrownOutlined, 
  FileTextOutlined, 
  DollarOutlined,
  ArrowUpOutlined,
  ArrowDownOutlined
} from '@ant-design/icons-vue';
import * as echarts from 'echarts/core';
import { LineChart, BarChart, PieChart } from 'echarts/charts';
import {
  TitleComponent,
  TooltipComponent,
  LegendComponent,
  GridComponent
} from 'echarts/components';
import { CanvasRenderer } from 'echarts/renderers';

// 定义类型接口


echarts.use([
  TitleComponent,
  TooltipComponent,
  LegendComponent,
  GridComponent,
  LineChart,
  BarChart,
  PieChart,
  CanvasRenderer
]);

export default {
  name: 'AdminDashboard',
  components: {
    UserOutlined,
    CrownOutlined,
    FileTextOutlined,
    DollarOutlined,
    ArrowUpOutlined,
    ArrowDownOutlined
  },
  setup() {
    const userChartRef = ref(null);
    const revenueChartRef = ref(null);
    const membershipChartRef = ref(null);
    const promptCategoryChartRef = ref(null);
    
    let userChart: echarts.ECharts | null = null;
    let revenueChart: echarts.ECharts | null = null;
    let membershipChart: echarts.ECharts | null = null;
    let promptCategoryChart: echarts.ECharts | null = null;
    
    const loading = ref(false);
    
    const statistics = reactive({
      totalUsers: 1258,
      userGrowth: 12.5,
      paidUsers: 386,
      paidUserGrowth: 8.3,
      totalPrompts: 5742,
      promptGrowth: 15.2,
      monthlyRevenue: 28650,
      revenueGrowth: 9.7
    });
    
    const recentActivities = ref([
      {
        title: '张三注册了账号',
        description: '新用户注册',
        time: '10分钟前',
        avatarColor: '#1890ff',
        avatarText: '用户'
      },
      {
        title: '李四升级了会员',
        description: '从基础版升级到专业版',
        time: '30分钟前',
        avatarColor: '#52c41a',
        avatarText: '会员'
      },
      {
        title: '王五创建了新提示词',
        description: '创建了"AI写作助手"提示词',
        time: '1小时前',
        avatarColor: '#722ed1',
        avatarText: '提示'
      },
      {
        title: '系统自动备份完成',
        description: '数据库每日备份',
        time: '2小时前',
        avatarColor: '#faad14',
        avatarText: '系统'
      },
      {
        title: '赵六取消了订阅',
        description: '取消了专业版订阅',
        time: '3小时前',
        avatarColor: '#f5222d',
        avatarText: '订阅'
      }
    ]);
    
    const initUserChart = () => {
      const chartDom = userChartRef.value;
      userChart = echarts.init(chartDom);
      
      const option = {
        tooltip: {
          trigger: 'axis'
        },
        legend: {
          data: ['总用户', '新增用户']
        },
        grid: {
          left: '3%',
          right: '4%',
          bottom: '3%',
          containLabel: true
        },
        xAxis: {
          type: 'category',
          boundaryGap: false,
          data: ['1月', '2月', '3月', '4月', '5月', '6月']
        },
        yAxis: {
          type: 'value'
        },
        series: [
          {
            name: '总用户',
            type: 'line',
            data: [820, 932, 1001, 1134, 1190, 1258],
            smooth: true,
            lineStyle: {
              width: 3,
              color: '#1890ff'
            },
            areaStyle: {
              color: {
                type: 'linear',
                x: 0,
                y: 0,
                x2: 0,
                y2: 1,
                colorStops: [
                  {
                    offset: 0,
                    color: 'rgba(24, 144, 255, 0.3)'
                  },
                  {
                    offset: 1,
                    color: 'rgba(24, 144, 255, 0.1)'
                  }
                ]
              }
            }
          },
          {
            name: '新增用户',
            type: 'line',
            data: [120, 112, 69, 133, 56, 68],
            smooth: true,
            lineStyle: {
              width: 3,
              color: '#52c41a'
            }
          }
        ]
      };
      
      userChart.setOption(option);
    };
    
    const initRevenueChart = () => {
      const chartDom = revenueChartRef.value;
      revenueChart = echarts.init(chartDom);
      
      const option = {
        tooltip: {
          trigger: 'axis',
          axisPointer: {
            type: 'shadow'
          },
          formatter: function(params) {
            return params[0].name + '<br/>' + params[0].seriesName + ': ¥' + params[0].value.toLocaleString();
          }
        },
        grid: {
          left: '3%',
          right: '4%',
          bottom: '3%',
          containLabel: true
        },
        xAxis: {
          type: 'category',
          data: ['1月', '2月', '3月', '4月', '5月', '6月']
        },
        yAxis: {
          type: 'value',
          axisLabel: {
            formatter: '¥{value}'
          }
        },
        series: [
          {
            name: '月收入',
            type: 'bar',
            data: [18500, 20300, 22100, 24800, 26100, 28650],
            itemStyle: {
              color: {
                type: 'linear',
                x: 0,
                y: 0,
                x2: 0,
                y2: 1,
                colorStops: [
                  {
                    offset: 0,
                    color: '#1890ff'
                  },
                  {
                    offset: 1,
                    color: '#36cfc9'
                  }
                ]
              }
            }
          }
        ]
      };
      
      revenueChart.setOption(option);
    };
    
    const initMembershipChart = () => {
      const chartDom = membershipChartRef.value;
      membershipChart = echarts.init(chartDom);
      
      const option = {
        tooltip: {
          trigger: 'item',
          formatter: '{a} <br/>{b}: {c} ({d}%)'
        },
        legend: {
          orient: 'vertical',
          right: 10,
          top: 'center',
          data: ['免费用户', '基础版', '专业版', '高级版']
        },
        series: [
          {
            name: '会员分布',
            type: 'pie',
            radius: ['50%', '70%'],
            avoidLabelOverlap: false,
            itemStyle: {
              borderRadius: 10,
              borderColor: '#fff',
              borderWidth: 2
            },
            label: {
              show: false,
              position: 'center'
            },
            emphasis: {
              label: {
                show: true,
                fontSize: '18',
                fontWeight: 'bold'
              }
            },
            labelLine: {
              show: false
            },
            data: [
              { value: 872, name: '免费用户', itemStyle: { color: '#d9d9d9' } },
              { value: 186, name: '基础版', itemStyle: { color: '#1890ff' } },
              { value: 142, name: '专业版', itemStyle: { color: '#52c41a' } },
              { value: 58, name: '高级版', itemStyle: { color: '#722ed1' } }
            ]
          }
        ]
      };
      
      membershipChart.setOption(option);
    };
    
    const initPromptCategoryChart = () => {
      const chartDom = promptCategoryChartRef.value;
      promptCategoryChart = echarts.init(chartDom);
      
      const option = {
        tooltip: {
          trigger: 'axis',
          axisPointer: {
            type: 'shadow'
          }
        },
        legend: {
          data: ['提示词数量']
        },
        grid: {
          left: '3%',
          right: '4%',
          bottom: '3%',
          containLabel: true
        },
        xAxis: {
          type: 'value',
          boundaryGap: [0, 0.01]
        },
        yAxis: {
          type: 'category',
          data: ['写作', '编程', '营销', '学习', '设计', '其他']
        },
        series: [
          {
            name: '提示词数量',
            type: 'bar',
            data: [1842, 1256, 986, 754, 612, 292],
            itemStyle: {
              color: function(params) {
                const colorList = [
                  '#1890ff', '#52c41a', '#faad14', 
                  '#722ed1', '#eb2f96', '#bfbfbf'
                ];
                return colorList[params.dataIndex];
              }
            }
          }
        ]
      };
      
      promptCategoryChart.setOption(option);
    };
    
    const handleResize = () => {
      userChart && userChart.resize();
      revenueChart && revenueChart.resize();
      membershipChart && membershipChart.resize();
      promptCategoryChart && promptCategoryChart.resize();
    };
    
    onMounted(() => {
      // 初始化图表
      setTimeout(() => {
        initUserChart();
        initRevenueChart();
        initMembershipChart();
        initPromptCategoryChart();
        
        window.addEventListener('resize', handleResize);
      }, 100);
    });
    
    onUnmounted(() => {
      window.removeEventListener('resize', handleResize);
      
      userChart && userChart.dispose();
      revenueChart && revenueChart.dispose();
      membershipChart && membershipChart.dispose();
      promptCategoryChart && promptCategoryChart.dispose();
    });
    
    return {
      statistics,
      recentActivities,
      loading,
      userChartRef,
      revenueChartRef,
      membershipChartRef,
      promptCategoryChartRef
    };
  }
};
</script>

<style scoped>
.admin-dashboard {
  padding: 24px;
}

.card-title {
  display: flex;
  align-items: center;
}

.card-title span {
  margin-left: 8px;
}

.card-content {
  display: flex;
  align-items: baseline;
  justify-content: space-between;
}

.card-value {
  font-size: 24px;
  font-weight: bold;
}

.card-trend {
  display: flex;
  align-items: center;
  font-size: 14px;
}

.card-trend.up {
  color: #52c41a;
}

.card-trend.down {
  color: #f5222d;
}

.trend-period {
  margin-left: 4px;
  color: rgba(0, 0, 0, 0.45);
}

.activity-time {
  color: rgba(0, 0, 0, 0.45);
  font-size: 12px;
  margin-top: 4px;
}

@media (max-width: 768px) {
  .admin-dashboard {
    padding: 12px;
  }
  
  .card-value {
    font-size: 20px;
  }
  
  .card-content {
    flex-direction: column;
    align-items: flex-start;
  }
  
  .card-trend {
    margin-top: 8px;
  }
}

@media (max-width: 576px) {
  .card-title {
    font-size: 14px;
  }
  
  .card-value {
    font-size: 18px;
  }
}
</style>